<!--
 * @Descripttion: 
 * @version: 
 * @Author: cyj
 * @Date: 2023-03-30 16:56:05
-->
<template>
  <view class="userdetail b" ref="user">
    <view class="top">
      <span class="back" @click='back'>
        <image src="../../static/images/common/back.png" mode=""></image>
      </span>
      <span class="title" v-if='userInfo.myid != userInfo.userid'>个人信息</span>
      <span class='title' v-if='userInfo.myid == userInfo.userid'>我的个人信息</span>
    </view>

    <view class="content-body">
      <view class="avater">
        <view class="left">
          <span>头像</span>
          <image :src="userInfo.avater" mode="" @click="updatedPic"></image>
          <div v-if="info.isShowPic">
            <qf-image-cropper :width="500" :height="500" :radius="30" @crop="handleCrop"></qf-image-cropper>
          </div>
        </view>
        <view class="right" v-if="userInfo.myid == userInfo.userid">
          <image src="@/static/images/common/more.png" mode=""></image>
        </view>
      </view>
      <view class="sign" @click="changeShow('签名',userInfo.userSign)">
        <view class="left">
          <span>签名</span>
          <span class="sign-content e">{{ userInfo.userSign }}</span>
        </view>
        <view class="right" v-if="userInfo.myid == userInfo.userid">
          <image src="@/static/images/common/more.png" mode=""></image>
        </view>
      </view>
      <view class="sign-time">
        <view class="left">
          <span>注册</span>
          <span class="e">{{ formatSignTime(userInfo.registerTime) }}</span>
        </view>
      </view>
      <view class="username" @click="changeShow('用户名', userInfo.userName)">
        <view class="left">
          <span>用户名</span>
          <span class="e">{{ userInfo.userName }}</span>
        </view>
        <view class="right" v-if="userInfo.userid == userInfo.myid">
          <image src="@/static/images/common/more.png" mode=""></image>
        </view>
      </view>
      <view class="name" @click="changeShow('昵称', userInfo.markname)" v-if="userInfo.userid != userInfo.myid">
        <view class="left">
          <span>昵称</span>
          <span class="e">{{ userInfo.markname }}</span>
        </view>
        <view class="right">
          <image src="@/static/images/common/more.png" mode=""></image>
        </view>
      </view>
      <view class="sex" @click="changeShow('性别', userInfo.sex)">
        <view class="left">
          <span>性别</span>
          <span class="e">{{ userInfo.sex }}</span>
        </view>
        <view class="right" v-if="userInfo.myid == userInfo.userid">
          <image src="@/static/images/common/more.png" mode=""></image>
        </view>
      </view>
      <view class="birday" @click="showData">
        <view class="left">
          <span>生日</span>
          <span class="e">{{ formatBirth(userInfo.birthday) }}</span>
        </view>
        <view class="right" v-if="userInfo.myid == userInfo.userid">
          <image src="@/static/images/common/more.png" mode=""></image>
        </view>

      </view>
      <view class="phone" @click="changeShow('电话', userInfo.phoneNum)">
        <view class="left">
          <span>电话</span>
          <span class="e">{{ userInfo.phoneNum}}</span>
        </view>
        <view class="right" v-if="userInfo.myid == userInfo.userid">
          <image src="@/static/images/common/more.png" mode=""></image>
        </view>
      </view>
      <view class="email" @click="changeShow('邮箱', userInfo.email)">
        <view class="left">
          <span>邮箱</span>
          <span class="e">{{ userInfo.email }}</span>
        </view>
        <view class="right" v-if="userInfo.myid == userInfo.userid">
          <image src="@/static/images/common/more.png" mode=""></image>
        </view>
      </view>
      <view class="password" @click="changeShow('密码', userInfo.password)" v-if='userInfo.myid == userInfo.userid'>
        <view class="left">
          <span>密码</span>
          <span class="e">{{ userInfo.password }}</span>
        </view>
        <view class="right" v-if="userInfo.myid == userInfo.userid">
          <image src="@/static/images/common/more.png" mode=""></image>
        </view>
      </view>
      <view class="layout">
        <button type='default' @click="quit" v-if='userInfo.userid == userInfo.myid'>退出登录</button>
        <button type='warn' @click="deleteFriend" v-if='userInfo.userid != userInfo.myid'>删除好友</button>
      </view>
    </view>

  </view>
  <!-- 日期组件 -->
  <uni-calendar ref="calendar" class="uni-calendar--hook" :clear-date="true" :insert="info.insert" @confirm="confirm" />

  <popupVue @getNewData='getNewData' :tempUserInfo='tempUserInfo' :isShowPopup='info.isShowPopup'></popupVue>

</template>

<script setup>
  import popupVue from '@/components/popup/popup.vue'
  import {
    formatSignTime,
    formatBirth
  } from '@/utils/formatDate'
  import {
    reactive,
    ref,
    getCurrentInstance,
  } from 'vue'
  import {
    onLoad,
    onShow
  } from '@dcloudio/uni-app'
  import {
    useUserStore
  } from '@/store/user.js'
  import {
    requestNet
  } from '@/api/base.js'
  import QfImageCropper from '@/uni_modules/qf-image-cropper/components/qf-image-cropper/qf-image-cropper.vue';
  const instance = getCurrentInstance()
  const user = useUserStore()
  const userInfo = reactive({
    userid: null, //查看对象id
    myid: null, //当前登录对象id
    token: '',
    avater: null,
    markname: '模拟的备注名',
    userSign: null,
    userName: null,
    sex: null,
    birthday: null,
    phoneNum: null,
    email: null,
    registerTime: null,
    password: '*******'
  })
  let tempUserInfo = reactive({
    propsName: '',
    attr: '',
    id: null,
  })
  //日期对象
  const info = reactive({
    insert: false,
    isShowPopup: false, //是否展示弹出层
    isShowPic: false,
  })
  const calendar = ref(null)
  //获取当前用户缓存信息
  function getNowUserInfo() {
    userInfo.myid = user.userinfo.userid
    userInfo.token = user.token
    //info.myname = user.userinfo.username
  }
  //退出登录
  function quit() {
    uni.showModal({
      title: '提示',
      content: '真的要退出登录吗?',
      success: function(res) {
        if (res.confirm) {
          //清空缓存
          uni.removeStorageSync('user')
          uni.navigateTo({ //跳转到登录页
            url: '/pages/login/login'
          })
        } else if (res.cancel) {
          return;
        }
      }
    });
  }
  //删除好友
  function deleteFriend() {
    uni.showModal({
      title: '提示',
      content: '确定删除该好友吗?',
      success: function(res) {
        if (res.confirm) {
          requestNet({
            url: '/add/deleteFriend',
            method: 'POST',
            data: {
              uid: userInfo.myid,
              fid: userInfo.userid
            },
            header: {
              token: userInfo.token
            }
          }).then(result => {
            let code = result.data.code
            if (code == 200) {
              uni.navigateTo({
                url: '/pages/home/home',
                icon: 'success'
              })
            } else {
              uni.showToast({
                title: result.data.message,
                icon: 'error'
              })
            }
          }, err => {
            console.log(err)
          })
        } else if (res.cancel) {
          return;
        }
      }
    });
  }

  //更新头像
  function updatedPic() {
    if (userInfo.myid != userInfo.userid) {
      uni.previewImage({
        urls: [userInfo.avater],
        longPressActions: {
          itemList: ['发送给朋友', '保存图片', '收藏'],
          success: function(data) {
            console.log(data)
          },
          fail: function(err) {
            console.log(err.errMsg);
          }
        }
      });
    } else {
      info.isShowPic = true
    }
  }

  function back() {
    uni.navigateTo({
      url: '/pages/reqfirend/reqfirend'
    })
  }
  //裁剪图片  点击确认之后
  function handleCrop(e) {
    userInfo.avater = e.tempFilePath
    //上传图片
    uni.uploadFile({
      url: `${instance.proxy.serverUrl}/files/upload`, //仅为示例，非真实的接口地址[后端接口地址]
      filePath: e.tempFilePath,
      name: 'file',
      formData: {
        url: 'user',
        // name: userInfo.myid
        name: new Date().getTime().toString() + userInfo.myid
      },
      header: {
        token: userInfo.token
      },
      success: (uploadFileRes) => {
        console.log(uploadFileRes)
        let picpath = uploadFileRes.data
        //保存到仓库中
        user.userinfo.imgurl = instance.proxy.serverUrl + picpath
        //调用后端
        updateUser(picpath, 'imgurl')
      }
    });
    uni.previewImage({
      urls: [e.tempFilePath],
      current: 0
    });
    info.isShowPic = false
  }

  //获取被查看用户的昵称
  function getSeeUserMarkName() {
    if (userInfo.myid == userInfo.userid) return;
    requestNet({
      url: '/user/getfriendName',
      data: {
        uid: userInfo.myid,
        fid: userInfo.userid
      },
      header: {
        token: userInfo.token
      }
    }).then(res => {
      let code = res.data.code
      let nickname = res.data.data[0].nickname
      if (code == 200) {
        userInfo.markname = nickname
      }
    }, err => {
      uni.showToast({
        title: err,
        icon: 'error'
      })
    })
  }

  //修改数据
  function updateUser(e, t, p = undefined) {
    requestNet({
      url: '/user/change',
      data: {
        userid: userInfo.userid,
        data: e,
        password: p,
        type: t
      },
      method: 'POST',
      header: {
        token: userInfo.token
      }
    }).then(res => {
      let code = res.data.code
      if (code == 200) {
        uni.showToast({
          title: '修改成功',
          icon: 'success'
        })
      } else {
        uni.showToast({
          title: res.data.message,
          icon: 'error'
        })
        return;
      }
    }).catch(err => {
      uni.showToast({
        title: err,
        icon: 'error'
      })
    })
  }

  //获取查看用户详细信息
  function getTargetUserInfo() {
    requestNet({
      url: '/user/userDetail',
      data: {
        userid: userInfo.userid
      },
      header: {
        token: userInfo.token
      }
    }).then(res => {
      let code = res.data.code
      let data = res.data.data[0]
      if (code == 200) {
        if (userInfo.myid == userInfo.userid) {
          user.userinfo = data //更新当前登录用户信息
        }
        if (data.imgurl.indexOf('data:image/jpg;base64,') != -1) { //图片是base64类型
          userInfo.avater = data.imgurl
        } else userInfo.avater = instance.proxy.serverUrl + data.imgurl
        userInfo.userSign = data.explain
        userInfo.userName = data.username
        userInfo.sex = data.sex
        userInfo.birthday = data.birth
        userInfo.phoneNum = data.phone
        userInfo.email = data.email
        userInfo.registerTime = data.registerTime
      }
    }).catch(err => {
      uni.showToast({
        title: err,
        icon: 'error'
      })
    })
  }

  //弹出日期弹出层
  function showData() {
    if (userInfo.myid != userInfo.userid) return;
    else calendar.value.open()
  }
  //确定选择日期
  function confirm(value) {
    userInfo.birthday = value.fulldate
    updateUser(value.fulldate, 'birth')
    getTargetUserInfo() //重新更新被查看用户的详细信息
  }
  //显示弹出层
  function changeShow(propsName, data) {
    if (userInfo.myid != userInfo.userid) { //不是当前用户，不能修改 除了备注名
      if (propsName == '昵称') {
        tempUserInfo.propsName = propsName
        tempUserInfo.attr = data
        tempUserInfo.id = userInfo.userid
        info.isShowPopup = !info.isShowPopup
      } else return
      return
    }
    tempUserInfo.propsName = propsName
    tempUserInfo.attr = data
    tempUserInfo.id = userInfo.userid
    info.isShowPopup = !info.isShowPopup
  }

  //处理子组件返回的新数据
  function getNewData(data) {
    let {
      propsName,
      value,
      password,
      newpwd
    } = data
    // console.log(data)
    if (propsName == '签名') {
      if (value == '') {
        value = '这个人很懒,什么都没有留下'
        userInfo.userSign = value
      } else userInfo.userSign = value
      //调用后端
      updateUser(value, `explain`)
    }
    if (propsName == '用户名') {
      userInfo.userName = value
      updateUser(value, 'username', password)
    }
    if (propsName == '昵称') {
      userInfo.markname = value
      requestNet({ //修改用户昵称
        url: '/user/updateFriendName',
        method: 'POST',
        data: {
          name: value,
          uid: userInfo.myid,
          fid: userInfo.userid
        },
        header: {
          token: userInfo.token
        }
      }).then(res => {
        if (res.data.code == 200) {
          uni.showToast({
            title: '修改昵称成功',
            icon: 'success'
          })
        }
      }, err => {
        uni.showToast({
          title: err,
          icon: 'error'
        })
      })
    }
    if (propsName == '性别') {
      if (value != '男' & value != '女') {
        uni.showToast({
          title: '性别输入错误,请重新输入',
          icon: 'error'
        })
        return;
      }
      userInfo.sex = value
      updateUser(value, 'sex')
    }
    if (propsName == '电话') {
      userInfo.phoneNum = value
      updateUser(value, 'phone')
    }
    if (propsName == '邮箱') {
      userInfo.email = value
      updateUser(value, 'email', password)
    }
    if (propsName == '密码') {
      updateUser(newpwd, 'password', password)
      //然后清空缓存，重新登录
      uni.removeStorageSync('user')
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/login/login'
        })
      }, 3000)
      return;
    }

    //修改当前用户之后再次获取用户信息并更新仓库中的数据
    if (userInfo.myid == userInfo.userid) { //如果不是修改当前用户，即更新组件内数据即可
      getTargetUserInfo() //更新当前登录用户信息
    }
  }

  onShow(() => {
    getTargetUserInfo() //获取被查看用户的详细信息
  })

  onLoad((e) => {
    if (e != null) {
      userInfo.userid = parseInt(e.id)
    }
    calendar.value = instance.refs.calendar
    getNowUserInfo() //获取当前用户详情
    getSeeUserMarkName() //获取被查看用户的昵称
  })
</script>

<style lang="scss" scoped>
  @import '@/assets/css/main.scss';

  .userdetail {
    padding: 0 20rpx;

    .top {
      position: relative;
      display: flex;
      align-items: center;
      height: 88rpx;
      border-bottom: 2rpx solid var(--text-color-grey);

      .back {
        display: inline-block;
        height: 48rpx;
        width: 48rpx;

        image {
          height: 100%;
          width: 100%;
        }
      }

      .title {
        position: absolute;
        //居中显示
        transform: translateX(-50%);
        left: 50%;

        font-size: 36rpx;
        font-weight: 700;
      }
    }

    .content-body {
      // margin-top: 20rpx;

      .avater,
      .sign,
      .sign-time,
      .name,
      .sex,
      .birday,
      .phone,
      .email,
      .password,
      .username {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 32rpx;

        .left {
          span {
            margin-right: 20rpx;
          }
        }
      }

      .avater {
        height: 140rpx;
        border-bottom: 2rpx solid var(--border-color);

        .left {
          display: flex;
          align-items: center;

          image {
            border-radius: 8px;
            height: 108rpx;
            width: 108rpx;
          }
        }
      }

      .sign {
        height: 110rpx;
        border-bottom: 2rpx solid var(--border-color);

        .left {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

      .sign-time,
      .name,
      .sex,
      .birday,
      .phone,
      .email,
      .password,
      .username {
        height: 100rpx;
        border-bottom: 2rpx solid var(--border-color);
      }

      .layout {
        margin-top: 40rpx;
        text-align: center;
      }
    }
  }

  .right {
    image {
      width: 28rpx;
      height: 28rpx;
    }
  }

  .e {
    color: var(--text-color-placeholder);
  }

  .popup[data-v-304119c4] {
    padding: 0;
  }

  .image-cropper[data-v-6592bb66] {
    z-index: 1;
  }

  uni-button[type='default'] {
    color: #ff0c1c;
    font-weight: 700;
  }
</style>
